package com.common.mybaits;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

/**
 * mybatis分页插件自动配置,日期自动填充
 * @author 大忽悠
 * @create 2022/10/9 11:29
 */
@Configuration
@Slf4j
@ConditionalOnClass({MybatisPlusInterceptor.class,PaginationInnerInterceptor.class})
public class MybatisAutoConfiguration {

    @ConditionalOnMissingBean(MybatisPlusInterceptor.class)
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        log.info("启用分页插件");
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    @ConditionalOnMissingBean(MetaObjectHandler.class)
    @Bean
    public DateMetaObjectHandler dateAutoFill(){
        return new DateMetaObjectHandler();
    }

    /**
     * 日期字段自动填充设置
     */
    public class DateMetaObjectHandler implements MetaObjectHandler
    {
        //插入时填充策略
        @Override
        public void insertFill(MetaObject metaObject) {
            this.setFieldValByName("createTime", LocalDateTime.now(),metaObject);
            this.setFieldValByName("updateTime",LocalDateTime.now(),metaObject);
        }

        //更新时填充策略
        @Override
        public void updateFill(MetaObject metaObject) {
            this.setFieldValByName("updateTime",LocalDateTime.now(),metaObject);
        }
    }
}
